

//更新seller和name，包括官方跟卖 getozondetail.js
//https://www.ozon.ru/getozonsearchid?auto_get=true
//登陆的情况下更新官方跟卖
//https://www.ozon.ru/getozonsearchid?auto_get=login

//更新评论 getozoncomment.js
//https://www.ozon.ru/updateozoncomment


//更新搜索结果 getozonapiajax.js
//https://www.ozon.ru/updateozon









//https://www.ozon.ru/api/entrypoint-api.bx/page/json/v2?url=%2Fmodal%2Fcity_selector%3Fneaf%3Df%26pv%3D0%26searchCity%3D%26select_location%3D0c5b2444-70a0-4932-980c-b4dc0d3f02b5%26sl_hash%3D8cf7715892577502208b2c24365ededca01cf78525448b414516210547812865%26src_main%3D%252Fsearch%252F%253F_fr%253D1696425234%2526deny_category_prediction%253Dtrue%2526from_global%253Dtrue%2526product_id%253D1097036949%2526text%253D%2525D0%25259F%2525D0%2525BE%2525D0%2525B4%2525D0%2525B2%2525D0%2525B5%2525D1%252581%2525D0%2525BD%2525D0%2525BE%2525D0%2525B9%252B%2525D1%252581%2525D0%2525B2%2525D0%2525B5%2525D1%252582%2525D0%2525B8%2525D0%2525BB%2525D1%25258C%2525D0%2525BD%2525D0%2525B8%2525D0%2525BA%26src_modal%3D%252Fmodal%252Faddressbook%253Fsrc_main%253D%25252Fsearch%25252F%25253F_fr%25253D1696425234%252526deny_category_prediction%25253Dtrue%252526from_global%25253Dtrue%252526product_id%25253D1097036949%252526text%25253D%252525D0%2525259F%252525D0%252525BE%252525D0%252525B4%252525D0%252525B2%252525D0%252525B5%252525D1%25252581%252525D0%252525BD%252525D0%252525BE%252525D0%252525B9%25252B%252525D1%25252581%252525D0%252525B2%252525D0%252525B5%252525D1%25252582%252525D0%252525B8%252525D0%252525BB%252525D1%2525258C%252525D0%252525BD%252525D0%252525B8%252525D0%252525BA%26page_changed%3Dtrue
// 爬虫拦截，如果禁用了，在一个主线程上操作，清空cookie，然后选择城市
var intervals = [];
var canstart1688=false;

var ozonGetQTime = {};
setInterval(() => {
    get1688Start();
}, 10000);

function addDataLock(time){
    dataLock = true;
    setTimeout(function() {
        dataLock = false;
    }, time); // 20秒钟后关闭标签页
}


function openIn1688Tab(url,time){
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('youyuan/index.htm'))
        if (tabsize){
            chrome.tabs.create({ url: url,windowId: tabsize.windowId} , function(tab) {
                setTimeout(function() {
                    chrome.tabs.remove(tab.id);
                }, time); // 20秒钟后关闭标签页
            });
        }
    });
}

var dataLock = false;
var lockTime = 0 ;

function get1688Start(){
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('https://s.1688.com/selloffer/offer_search.html?auto_get=true'))
        if (tabsize){
            $.ajax({
                url: "http://test.com:8888/index.php?c=api/neiyi/shein_1688_get&tabid="+tabsize.id,
                success: function (data) {
                    console.log(data.data);
                    chrome.tabs.sendMessage(tabsize.id, data);
                }
            });

        }
    });
}
//set1688Interval();

function searchAmazonDetail(offerList,index,page){

    var offerItem = offerList[index];
    console.log(index+"__"+page);
    setTimeout(function() {
        var url = "https://www.amazon.com"+offerItem['url']+".&auto_get=true";

        chrome.tabs.query({}, function(tabs){
            const tabsize = tabs.find(v => v.url.includes('https://www.amazon.com/s?k='))
            chrome.tabs.create({url: url,windowId: tabsize.windowId} , function(tab) {
                setTimeout(function() {
                    chrome.tabs.remove(tab.id);
                }, 10000); // 20秒钟后关闭标签页
            });
        });


        if(index<(offerList.length-1)){
            searchAmazonDetail(offerList,index+1,page);
        }else{
            console.log("start next page:" + (page+1));
            chrome.tabs.query({}, function(tabs){
                const tabsize = tabs.find(v => v.url.includes('https://www.amazon.com/s?k='))
                console.log("start next page tabsize:" + (tabsize));
                if (tabsize){
                    chrome.tabs.sendMessage(tabsize.id, page+1)
                }
            });
        }
    }, 5000); // 20秒钟后关闭标签页
}


function searchImgByApi(offerList,index,page,keyword){
    console.log("_searchImgByApi"+index+"_page"+page);
    var offerItem = offerList[index];
    var pic = offerItem['image']['imgUrlOf290x290'];
    setTimeout(function() {
        var url = "https://detail.1688.com/offer/"+offerItem['id']+".html?auto_get=true";
        chrome.tabs.query({}, function(tabs){
            const tabsize = tabs.find(v => v.url.includes('selloffer/offer_search.htm?keywords'))
            chrome.tabs.create({url: url,windowId: tabsize.windowId} , function(tab) {
                setTimeout(function() {
                    chrome.tabs.remove(tab.id);
                }, 10000); // 20秒钟后关闭标签页
            });
        });



        if(index<(offerList.length-1)){
            searchImgByApi(offerList,index+1,page,keyword);
        }else{
            chrome.tabs.query({}, function(tabs){
                const tabsize = tabs.find(v => v.url.includes('selloffer/offer_search.htm?keywords'))
                if (tabsize){
                    chrome.tabs.sendMessage(tabsize.id, page+1)
                }
            });
        }
    }, 5000); // 20秒钟后关闭标签页

    /*$.ajax({
             url: "https://www.gongrenbao.cn/index.php?c=api/ozon/ozonpicsearch",
             data: {
                pic: pic,
                id: offerItem['id'],
                keyword:keyword,
                price: offerItem['tradePrice']['offerPrice']['priceInfo']['price'],
                title:offerItem['information']['subject']
              },
              error: function(err) {
                    console.error(err)
              },
             success: function (data) {
                console.log(offerList);
                console.log(index);
                 console.log(offerList.length);
                if(index<(offerList.length-1)){
                    searchImgByApi(offerList,index+1,page,keyword);
                }else{
                    chrome.tabs.query({}, function(tabs){
                      const tabsize = tabs.find(v => v.url.includes('selloffer/offer_search.htm?keywords'))
                      if (tabsize){
                           chrome.tabs.sendMessage(tabsize.id, page+1)
                      }
                    });
                }

             }
     });*/
}

function getozonseller(sender){
    $.get("http://47.94.147.93/index.php?c=api/ozon/getozonseller&tabid="+sender.tab.id,
        function(data){
            console.log(data);
            var dataobj = JSON.parse(data);
            if(dataobj.data.url){
                var url = "https://www.ozon.ru/seller/"+dataobj.data.seller_id+"/products/?miniapp=seller_"+dataobj.data.seller_id;
                console.log(url);
                chrome.tabs.sendMessage(sender.tab.id, dataobj)
            }else{
                setTimeout(function() {
                    getozonseller(sender)
                }, 20000);
            }
        },
        "text").fail(function(xhr, error) {
        // 处理错误的回调函数
        console.log(xhr.statusText);
        console.log(error);
        setTimeout(function() {
            getozonseller(sender)
        }, 20000);
    });
}
/*
function ozonNexQPage(sender){
    ozonGetQTime[sender.tab.id] =  Math.floor(new Date().getTime() / 1000);
    console.log(sender);
     if(ozon403lock==true){
        setTimeout(function() {
                ozonNexQPage(sender)
        }, 2000);
        return;
     }
     $.get("http://8.147.107.250/index.php?c=api/erp/follow/search_follow_get&tabid="+sender.tab.id,
          function(data){
            console.log(data);
                var dataobj = JSON.parse(data);

                if(dataobj && dataobj.data && dataobj.data.q && dataobj.data.q!='null'){
                    console.log(follow_sku_id_post_ing);
                    console.log(dataobj.data.sku_id);

                    if(follow_sku_id_post_ing.has(dataobj.data.sku_id)){

                         setTimeout(function() {
                            ozonNexQPage(sender)
                          }, 20000);
                    }else{


                        var url = "https://www.ozon.ru/highlight/tovary-iz-kitaya-935133/?from_global=true&text="+dataobj.data.q+"&category="+dataobj.data.cate
                        console.log(url);
                        chrome.tabs.sendMessage(sender.tab.id, url)
                    }
                }else{
                     setTimeout(function() {
                        ozonNexQPage(sender)
                      }, 20000);
                }

          },
      "text").fail(function(xhr, error) {
                // 处理错误的回调函数
                console.log(xhr.statusText);
                console.log(error);
                setTimeout(function() {
                    ozonNexQPage(sender)
              }, 20000);
        });
}*/

function formatTimestampToYMDHMS(timestamp) {
    let date = new Date(timestamp); // 将时间戳转换为 Date 对象
    return date.toISOString(); // 返回标准的年月日时分秒格式
}


var blockTime = new Map();
var search_follow_post_time =search_follow_get_time = search_follow_get_init_time = Date.now();
setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('https://www.ozon.ru/getsearchfollow'))
        if (tabsize){
            let currentTime = Date.now();
            let elapsedTime = (search_follow_get_time - search_follow_post_time) / 1000;
            let noGetTime = (Date.now() - search_follow_get_time)/1000;
            console.log("getsearchfollow no post time:"+elapsedTime)
            console.log("getsearchfollow no get time:"+noGetTime)
            console.log("search_follow_get_time:"+formatTimestampToYMDHMS(search_follow_get_time));
            console.log("search_follow_post_time:"+formatTimestampToYMDHMS(search_follow_post_time));
            if (elapsedTime >= 600) {//600秒一直没有消息
                console.log("search_follow_get_time reload elapsedTime > 600");
                chrome.tabs.reload(tabsize.id);
                search_follow_post_time = Date.now();
            }else if(search_follow_get_time==search_follow_post_time && search_follow_get_time == search_follow_get_init_time){
                chrome.tabs.reload(tabsize.id);
                console.log("search_follow_get_time reload same time");
                search_follow_post_time = Date.now();
            }else if(noGetTime > 600){
                chrome.tabs.reload(tabsize.id);
                console.log("search_follow_get_time reload noGetTime > 600");
                search_follow_post_time =search_follow_get_time = Date.now();
            }
        }
    });
}, 30000);

var last_job_id = 0 ;
function ozonNextQAjax(sender,job_id){
    if(ozon403lock==true){
        console.log("ozonNextQAjax ozon403lock");
        setTimeout(function() {
            ozonNextQAjax(sender,job_id)
        }, 20000);
        return;
    }

    console.log("job_id:"+job_id + " last_job_id:"+last_job_id);
    if(job_id>last_job_id){
        last_job_id= job_id;
    }else if(job_id < last_job_id){
        return;
    }

    search_follow_get_time = Date.now();
    $.get("http://8.147.107.250/index.php?c=api/erp/follow/search_follow_get&tabid="+sender.tab.id,
        function(data){
            console.log(data);
            var dataobj = JSON.parse(data);
            if(dataobj && dataobj.data && dataobj.data.q && dataobj.data.q!='null'){

                console.log(follow_sku_id_post_ing);
                console.log(dataobj.data.sku_id);

                if(follow_sku_id_post_ing.has(dataobj.data.sku_id)){

                    var skuFollowBlockTime = blockTime.get(dataobj.data.sku_id);
                    if(!skuFollowBlockTime){
                        skuFollowBlockTime = 0;
                    }
                    blockTime.set(dataobj.data.sku_id,skuFollowBlockTime++)


                    if(skuFollowBlockTime > 20){
                        follow_sku_id_post_ing.delete(dataobj.data.sku_id)
                    }

                    console.log("follow_sku_id_post_ing has sku_id,ozonNexQPage after 20 s");
                    console.log("follow_sku_id_post_ing has sku_id "+dataobj.data.sku_id+" blockTime time :"+skuFollowBlockTime);
                    setTimeout(function() {
                        ozonNextQAjax(sender,job_id)
                    }, 20000);
                }else{

                    console.log("follow_sku_id_post_ing not has sku_id----sendMessage!");
                    dataobj.job_id = job_id;
                    chrome.tabs.sendMessage(sender.tab.id, dataobj)
                }

            }else{
                setTimeout(function() {
                    ozonNextQAjax(sender,job_id)
                }, 10000);
            }

        },
        "text").fail(function(xhr, error) {
        // 处理错误的回调函数
        console.log(xhr.statusText);
        console.log(error);
        setTimeout(function() {
            ozonNextQAjax(sender,job_id)
        }, 10000);
    });
}


var lastSpamTime = 0;
var spanTabIds = [];

var ozon403lock = false;

function ozon403killcookie(){
    chrome.cookies.getAll({domain: '.ozon.ru'}, function(cookies) {
        for (var i = 0; i < cookies.length; i++) {
            console.log("remove cookie:"+cookies[i].name)
            chrome.cookies.remove({
                url: "https://www.ozon.ru" + cookies[i].path,
                name: cookies[i].name
            },function(details) {
                if (details === null) {
                    console.log('Cookie not removed');
                } else {
                    console.log('Cookie removed:', details);
                }
            });
        }
    });
}


//防止403状态不更新，定时检查
setInterval(() => {

    console.log("定时检查 dospam窗口是否存在");
    if(ozon403lock == false){
        console.log("no lock");
        return;
    }

    var spamUrl = "https://www.ozon.ru/dospam";
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes(spamUrl));

        if (!tabsize){
            console.log("dospam窗口不存在，新增");
            chrome.tabs.create({ url: spamUrl} , function(tab) {
                //加载js
                setTimeout(function() {
                    chrome.tabs.remove(tab.id);
                }, 300000);
            });

        }else{
            console.log("dospam窗口已经存在");
            chrome.tabs.sendMessage(tabsize.id, { action: 'doSpamPage' });
        }
    });
}, 30000);

//403错误拦截处理
function ozonapi403(sender){
    if(ozon403lock == true){
        console.log("have lock");
        return;
    }
    ozon403lock = true;
    var spamUrl = "https://www.ozon.ru/dospam";
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes(spamUrl));

        if (!tabsize){
            //如果没有窗口，弹出一个新窗口做拦截判断，并且发送一个消息
            $.ajax({
                url: "https://www.gongrenbao.cn/index.php?c=api/ozon/error403",
                type: "GET",
                success: function (data) {
                    console.log(data);
                }
            });
            console.log("set ozon403lock true");
            ozon403killcookie();

            setTimeout(function() {
                if(sender){
                    chrome.tabs.create({ url: spamUrl,windowId: sender.tab.windowId} , function(tab) {
                        //加载js
                        setTimeout(function() {
                            chrome.tabs.remove(tab.id);
                        }, 300000);
                    });
                }else{
                    chrome.tabs.create({ url: spamUrl} , function(tab) {
                        //加载js
                        setTimeout(function() {
                            chrome.tabs.remove(tab.id);
                        }, 300000);
                    });
                }

            }, 2000);

        }else{
            console.log("dospam窗口已经存在");
            chrome.tabs.sendMessage(tabsize.id, { action: 'doSpamPage' });
        }
    });
}

/*

//监听地址，加载js文件
chrome.webRequest.onBeforeRequest.addListener(
  function(details) {
    if (details.url.startsWith("https://www.ozon.ru/dospam")) {
      console.log(details.url+" start load scripts");
      chrome.tabs.executeScript(details.tabId, {file: 'jquery.min.js'}, function() {
          console.log('jquery.min.js scripts loaded successfully!');
          // jquery.min.js 文件加载完成后，再加载 ozondospam.js 文件
          chrome.tabs.executeScript(details.tabId, {file: 'ozondospam.js'}, function() {

            setTimeout(function() {
                chrome.tabs.sendMessage(details.tabId, { action: 'doSpamPage' });
             }, 2000); // 20秒钟后关闭标签页
            console.log('All scripts loaded successfully!');
          });
        });
    }
  },
  { urls: ["<all_urls>"] },
  ["blocking"]
);
*/


function ozon_spm_ok(){
    ozon403lock = false;
    console.log(" ozon_spm_ok !!");
}

chrome.runtime.onMessage.addListener(async (msg, sender) => {

    console.log("msg:type=" + msg.data.type);
    if (msg.data) {
        if(msg.data.type=='goat'){
            $.post("https://www.gongrenbao.cn/index.php?c=api/du/updatesku&",
                {spu_id:msg.data.id,data:msg.data.body},
                function(data){
                    console.log(data);
                },
                "text");
        }else if( msg.data.type=='du'){

            $.post("https://www.gongrenbao.cn/index.php?c=api/du/updatedusku&",
                {spu_id:msg.data.id,data:msg.data.body},
                function(data){
                    console.log(data);
                },
                "text");
        }else if( msg.data.type=='dusize'){

            $.post("https://www.gongrenbao.cn/index.php?c=api/du/updateduskusize&",
                {spu_id:msg.data.id,data:msg.data.body},
                function(data){
                    console.log(data);
                },
                "text");
        }else if( msg.data.type=='img1688'){

            $.post("https://test.com/index.php?c=api/ozon/update1688img&rand=123",
                {data:msg.data.body , pic_url:msg.data.pic_url},
                function(data){
                    console.log(data);
                },
                "text");
        }else if(msg.data.type=='search_follow_post'){
            search_follow_post_time = new Date().getTime();
            add_follow_queue(msg);
        }else if( msg.data.type=='sheindata1688'){
            $.post("http://test.com:8888/index.php?c=api/neiyi/shein_detail_1688_post",
                {data:msg.data.body , id:msg.data.id},
                function(data){
                    console.log(new Date() + " " );
                    console.log(data);
                },
                "text");
        }else if( msg.data.type=='data1688' || msg.data.type=='data1688amazon'){

            console.log("get data1688 amazon_id:" + msg.data.amazon_id);
            console.log(msg.data.body.url);
            if(msg.data.body.url){
                if (msg.data.body.url.indexOf("https://g.alicdn.com/sd/punish/deny_h5.html") != -1 ){
                    openIn1688Tab("https://www.1688.com/",60000)
                    addDataLock(60000);
                }else{
                    var openurl = "https://search.1688.com/"+msg.data.body.url;
                    openIn1688Tab(openurl,20000)
                    addDataLock(20000);
                }
            }else{
                if(msg.data.type=='data1688amazon'){
                    $.post("http://47.94.147.93/index.php?c=api/ozon/update1688amazon",
                        {data:msg.data.body , amazon_id:msg.data.amazon_id},
                        function(data){
                            console.log(new Date() + " " );
                            //  console.log(data);
                        },
                        "text");
                }else{

                    $.post("http://47.94.147.93/index.php?c=api/ozon/update1688",
                        {data:msg.data.body , pic_url:msg.data.pic_url},
                        function(data){
                            //  console.log(data);
                        },
                        "text");
                }

            }

        }else if( msg.data.type=='ozonfirstpage'){
            console.log("ozonfirstpage");
            ;
        }else if( msg.data.type=='ozonlist'){
            console.log("ozonlist");
            //console.log(msg.data);

        }else if( msg.data.type=='getozonseller'){
            getozonseller(sender);
        }else if( msg.data.type=='get1688forsearch'){
            searchImgByApi(msg.data.body,0,msg.data.page,msg.data.keyword);
        }else if( msg.data.type=='ozon_spm'){
            ozon_spm();
        }  else if( msg.data.type=='ozonspuimg'){

            $.post("http://47.94.147.93/index.php?c=api/ozon/upozonspuimg",
                {data:msg.data.body,cate:msg.data.category},
                function(data){
                    console.log(data);
                },
                "text");
        }else if( msg.data.type=='getamazon'){
            $.post("http://47.94.147.93/index.php?c=api/ozon/upozonamazon",
                {data:msg.data.data,q:msg.data.q},
                function(data){
                    console.log(data);
                    if(msg.skip_fetch_detail==false){
                        searchAmazonDetail(msg.data.data,0,msg.data.page);
                    }

                },
                "text");
        }else if( msg.data.type=='1688detail'){

            $.post("https://test.com/index.php?c=api/ozon/upozonspu&type=firstpage",
                {data:msg.data.body,cate:msg.data.category},
                function(data){
                    console.log(data);
                },
                "text");
        }else if( msg.data.type=='updateOzonComment'){
            $.post("http://47.94.147.93/index.php?c=api/ozon/upozoncomment",
                {data:msg.data.body,sku_id:msg.data.sku_id},
                function(data){
                    console.log(data);
                },
                "text");
        }else if( msg.data.type=='getfollowdetail'){
            page_follow_post_time = new Date().getTime();
            $.post("http://8.147.107.250/index.php?c=api/erp/follow/page_follow_post&no_sesion=1&sku_id="+msg.data.sku,
                {data:msg.data.body,sku:msg.data.sku},
                function(data){
                    console.log(data);
                },
                "text");
        }else if( msg.data.type=='ozontemplate'){
            $.post("http://8.147.107.250/index.php?c=api/erp/template/template_post&no_sesion=1&sku_id="+msg.data.sku,
                {data:msg.data.body,sku:msg.data.sku},
                function(data){
                    console.log(data);
                },
                "text");
        }else if( msg.data.type=='getfollowitemstatus'){
            item_follow_post_time = new Date().getTime();
            $.post("http://8.147.107.250/index.php?c=api/erp/follow/item_follow_post&no_sesion=1&sku_id="+msg.data.sku,
                {status:msg.data.status,sku:msg.data.sku},
                function(data){
                    console.log(data);
                },
                "text");//getfollowitemstatus
        }else if( msg.data.type=='ozondetaillogin'){
            $.post("http://47.94.147.93/index.php?c=api/ozon/upozondetail&login=1",
                {data:msg.data.body,sku:msg.data.sku},
                function(data){
                    console.log(data);
                },
                "text");
        }else if( msg.data.type=='ozon_font_cate_type_post'){
            $.post("http://8.147.107.250/index.php?c=api/erp/cate/ozon_font_cate_type_post",
                {data:msg.data.body,type_id:msg.data.type_id},
                function(data){
                    console.log(data);
                },
                "text");
        } else if( msg.data.type=='spam_check_and_click'){
            spam_check_and_click(sender);
        }else if( msg.data.type=='ozonapi403'){
            ozonapi403(sender);
        }else if( msg.data.type=='ozon403killcookie'){
            ozon403killcookie(sender);
        } else if( msg.data.type=='ozon_spm_ok'){
            ozon_spm_ok(sender);
        }else if( msg.data.type=='getamazonend'){//ozonNextQ
            console.log(msg.data);
            $.get("http://47.94.147.93/index.php?c=api/ozon/getmanagesearchq&q="+msg.data.q,
                function(data){
                    console.log(data);
                    var dataobj = JSON.parse(data);
                    console.log(dataobj);
                    var url = "https://www.amazon.com/s?k="+dataobj.data.nextQ+"&s=exact-aware-popularity-rank&rh=p_36%3A3000-&auto_get=true"
                    console.log(url);
                    chrome.tabs.create({ url: url,windowId: sender.tab.windowId} , function(tab) {

                    });
                },
                "text");
        } else if( msg.data.type=='ozonNextQAjax'){
            ozonNextQAjax(sender,msg.data.job_id);
        } else if( msg.data.type=='ozonNextQ'){//ozonNextQ
            ozonNexQPage(sender);
        }  else if( msg.data.type=='ozonLive'){//ozonNextQ
            ozonGetQTime[sender.tab.id] =  Math.floor(new Date().getTime() / 1000);
        } else if( msg.data.type=='getamazonsubcateend'){
            console.log(msg.data);
            $.get("http://47.94.147.93/index.php?c=api/ozon/getamazoncate&cate="+msg.data.cate,
                function(data){
                    console.log(data);
                    var dataobj = JSON.parse(data);
                    console.log(dataobj);
                    var url = "https://www.amazon.com/s?rh=n%3A"+dataobj.data.nextCate+"%2Cp_36%3A3000-&s=exact-aware-popularity-rank&auto_get=true"
                    console.log(url);
                    chrome.tabs.create({ url: url,windowId: sender.tab.windowId} , function(tab) {

                    });
                },
                "text");
        }else if( msg.data.type=='upozonhotitem'){
            console.log(msg);
            $.post("http://8.147.107.250/index.php?c=api/ozon/upozonhotitem&no_sesion=1",
                JSON.stringify(msg.data.data),
                function(data){
                    console.log(data);
                },
                "text");
        }else if( msg.data.type=='upozonhotquery'){
            console.log(msg);
            $.post("http://8.147.107.250/index.php?c=api/erp/data/update_query_data&no_sesion=1",
                JSON.stringify(msg.data.data),
                function(data){
                    console.log(data);
                },
                "text");
        }else if( msg.data.type=='sheindetail'){
            console.log(msg);
            clearSheinLock();
            $.post("http://47.94.147.93/index.php?c=api/neiyi/shein_detail_post&no_sesion=1",
                JSON.stringify(msg.data.data),
                function(data){
                    console.log(data);
                },
                "text");
        }else if( msg.data.type=='sheindetaildel'){
            console.log(msg);
            $.post("http://47.94.147.93/index.php?c=api/neiyi/shein_detail_post&type=del&no_sesion=1",
                JSON.stringify(msg.data.data),
                function(data){
                    console.log(data);
                },
                "text");
        }
        else if( msg.data.type=='sheinlist'){
            console.log(msg);
            $.post("http://47.94.147.93/index.php?c=api/neiyi/shein_list_post&no_sesion=1&type="+msg.data.cate+"&sort="+msg.data.sort+"&page="+msg.data.page+"&path="+msg.data.path,
                JSON.stringify(msg.data.data),
                function(data){
                    console.log(data);
                },
                "text");
        }else if( msg.data.type=='sheinblock'){
            console.log(msg);
            setSheInBlock("hk");
        }else if( msg.data.type=='sheinblock_yn'){
            console.log(msg);
            setSheInBlock("yn");
        }else if( msg.data.type=='sheinblock_sheinlevel'){
            console.log(msg);
            setSheInBlock("shein_level");
        }else if( msg.data.type=='sheinblock_yuenanstock'){
            console.log(msg);
            yuenanstock_block_time = msg.data.block_time_int;
            setSheInBlock("yuenanstock");
        }else if( msg.data.type=='sheinstock'){
            console.log(msg);
            $.post("http://test.com:8888/index.php?c=api/neiyi/shein_detail_stock_post&no_sesion=1&id="+msg.data.id,
                JSON.stringify(msg.data.stock_map),
                function(data){
                    console.log(data);
                },
                "text");
        }else if( msg.data.type=='sheinstock_s1'){
            console.log(msg);
            clearSheinLockYn();
            $.post("http://47.94.147.93/index.php?c=api/neiyi/shein_s1_detail_stock_post&no_sesion=1&id="+msg.data.id+"&price="+msg.data.price,
                JSON.stringify(msg.data.stock_map),
                function(data){
                    //console.log(data);
                },
                "text");
        }else if( msg.data.type=='sheinstock_s1_new_url'){
            console.log(msg);
            clearSheinLockYn();
            $.post("http://47.94.147.93/index.php?c=api/neiyi/shein_s1_new_url_post&no_sesion=1&id="+msg.data.id+"&price="+msg.data.price,
                JSON.stringify(msg.data.all_color_list),
                function(data){
                    //console.log(data);
                },
                "text");
        }else if( msg.data.type=='sheinstock_my'){
            console.log(msg);
            clearSheinLockYn();
            $.post("http://47.94.147.93/index.php?c=api/neiyi/shein_my_detail_stock_post&no_sesion=1&id="+msg.data.id+"&price="+msg.data.price,
                JSON.stringify(msg.data.stock_map),
                function(data){
                    //console.log(data);
                },
                "text");
        }
        else if( msg.data.type=='shein_user_size'){
            console.log(msg);``
            $.post("http://47.94.147.93/index.php?c=api/neiyi/shein_user_size_post&no_sesion=1&id="+msg.data.id,
                JSON.stringify(msg.data.user_size),
                function(data){
                    console.log(data);
                },
                "text");
        }
        else if( msg.data.type=='du_sku_info'){
            console.log(msg);
            $.post("http://47.94.147.93/index.php?c=api/xiangshui/du_post",
                JSON.stringify(msg.data.data),
                function(data){
                    console.log(data);
                },
                "text");
        }else if( msg.data.type=='du_brand_info'){
            console.log(msg);
            $.post("http://47.94.147.93/index.php?c=api/xiangshui/brand_post",
                JSON.stringify(msg.data.data),
                function(data){
                    console.log(data);
                },
                "text");
        }else if(msg.data.type==='focusTab'){

            console.log(sender.tab.windowId,sender.tab.id);
            // 激活窗口并聚焦标签
            chrome.windows.update(sender.tab.windowId, { focused: true });
            chrome.tabs.update(sender.tab.id, { active: true });

            return { success: true };
        }







        /*else if( msg.data.type=='1688canstart'){
            console.log("canstart1688_"+canstart1688);
            if(canstart1688==false){
                canstart1688 = true;
                get1688Start();
            }
        }*/

    }

    //console.log(msg)
    if (msg.close) {
        chrome.tabs.remove(sender.tab.id)
    }
})



/*


setInterval(() => {
  // 发送给 popup
  chrome.runtime.sendMessage('tab110 ok')
  chrome.tabs.query({}, function(tabs){
      const tab110 = tabs.find(v => v.url.includes('110'))
      if (tab110){
         $.ajax({
             url: "https://www.gongrenbao.cn/index.php?c=api/du/goatspu",
             type: "GET",
             success: function (data) {
                console.log(data);
                chrome.tabs.sendMessage(tab110.id, data)
             }
        });
      }
     } );
}, 10000);


setInterval(() => {
  // 发送给 popup
  chrome.runtime.sendMessage('tabadmn ok')
  chrome.tabs.query({}, function(tabs){
      const tabadmn = tabs.find(v => v.url.includes('cross-spot-goods'))
      if (tabadmn){
         $.ajax({
             url: "https://www.gongrenbao.cn/index.php?c=api/du/duspu",
             type: "GET",
             success: function (data) {
                console.log(data);
                chrome.tabs.sendMessage(tabadmn.id, data)
             }
        });
      }
    });

}, 20000);




setInterval(() => {
  // 发送给 popup
  chrome.runtime.sendMessage('tabsize ok')
  chrome.tabs.query({}, function(tabs){
      const tabsize = tabs.find(v => v.url.includes('main/bid-log'))
      if (tabsize){
         $.ajax({
             url: "https://www.gongrenbao.cn/index.php?c=api/du/duspunosize",
             type: "GET",
             success: function (data) {
                console.log(data);
                chrome.tabs.sendMessage(tabsize.id, data)
             }
        });
      }
    });

}, 10000);

*/
/*

setInterval(() => {

    chrome.tabs.query({}, function(tabs){
      const tabsize = tabs.find(v => v.url.includes('selloffer/offer_search'))
      if (tabsize){
         $.ajax({
             url: "https://test.com/index.php?c=api/ozon/get1688imgid",
             dataType: "jsonp",
             success: function (data) {
                console.log(data);
                console.log(tabsize);
                chrome.tabs.sendMessage(tabsize.id, data)
             }
        });
      }
    });
}, 10000);
*/


/*
setInterval(() => {
    chrome.tabs.query({}, function(tabs){
      const tabsize = tabs.find(v => v.url.includes('detail.1688.com/offer/'))
      if (tabsize){
         chrome.tabs.executeScript(tabsize.id, { code: "console.log(window.__INIT_DATA);" }, function(result) {
              // 回调函数中可以检查脚本是否正确执行
              console.log(result);
            });
         *//*$.ajax({
             url: "https://www.gongrenbao.cn/index.php?c=api/ozon/get1688",
             dataType: "jsonp",
             success: function (data) {
                console.log(data);
                console.log(tabsize);
                chrome.tabs.sendMessage(tabsize.id, data)
             }
        });*//*
      }
    });
}, 10000);*/


/*

setInterval(() => {
    chrome.tabs.query({}, function(tabs){
      const tabsize = tabs.find(v => v.url.includes('detail.1688.com/offer/'))
      if (tabsize){
         chrome.tabs.executeScript(tabsize.id, { code: "console.log(window.__INIT_DATA);" }, function(result) {
              // 回调函数中可以检查脚本是否正确执行
              console.log(result);
            });
         *//*
*/
/*$.ajax({
             url: "https://www.gongrenbao.cn/index.php?c=api/ozon/get1688",
             dataType: "jsonp",
             success: function (data) {
                console.log(data);
                console.log(tabsize);
                chrome.tabs.sendMessage(tabsize.id, data)
             }
        });*//*
*/
/*
      }
    });
}, 10000);
*/




/*
setInterval(() => {
    chrome.tabs.query({}, function(tabs){
      const tabsize = tabs.find(v => v.url.includes('https://s.1688.com/selloffer/offer_search.html'))
      if (tabsize){
          $.ajax({
             url: "http://47.94.147.93/index.php?c=api/ozon/get1688forcatematch&tabid="+tabsize.id,
             success: function (data) {
                chrome.tabs.sendMessage(tabsize.id, data);
             }
        });
      }
    });
}, 10000);*/


setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('/updateozoncomment'))
        if (tabsize){
            if(ozon403lock==false){
                $.ajax({
                    url: "http://47.94.147.93/index.php?c=api/ozon/getozonskucomment&tabid="+tabsize.id,
                    success: function (data) {
                        chrome.tabs.sendMessage(tabsize.id, data);

                        /*if(data.data.sku_id){
                            var url = "https://ozon.ru/product/" + data.data.sku_id;
                            console.log(url);
                                chrome.tabs.create({ url: url,windowId: tabsize.windowId} , function(tab) {
                                      setTimeout(function() {
                                        chrome.tabs.remove(tab.id);
                                      }, 60000); // 20秒钟后关闭标签页
                          });
                        }*/

                    }
                });
            }else{
                console.log("updateozoncomment ozon403lock");
            }

        }
    });
}, 10000);


setInterval(() => {
    console.log(ozonGetQTime);
    for (var key in ozonGetQTime) {
        var tabId = key;
        var lastUpdateTime = ozonGetQTime[key];
        var timeNow = Math.floor(new Date().getTime() / 1000);
        console.log(timeNow - lastUpdateTime)
        console.log(tabId)
        console.log(timeNow - lastUpdateTime > 1800);
        //十分钟没更新了，刷新一下页面防止假死，如果超过一小时没有更新不用检测了
        if(timeNow - lastUpdateTime > 1800 && timeNow - lastUpdateTime < 3600){
            chrome.tabs.query({url: 'https://www.ozon.ru/highlight/tovary-iz-kitaya-*'}, function(tabs) {
                if (tabs && tabs.length > 0) {
                    for (var i = 0; i < tabs.length; i++) {
                        if(tabs[i].id == tabId){
                            console.log('realod_'+tabs[i].id)
                            chrome.tabs.reload(tabs[i].id, {bypassCache: false}, function() {
                                console.log("Tab reloaded with cache");
                            });
                        }
                    }
                }
            });
        }
    }
}, 60000);

setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('/updateamazondesc'))
        if (tabsize){
            $.ajax({
                url: "http://8.147.107.250/index.php?c=api/ozon/getamazonnodesc&no_sesion=1",
                success: function (data) {
                    if(data.data.data.path){
                        var url = "https://www.amazon.com" + data.data.data.path +"?auto_get=true&amazon_id="+data.data.data.amazon_id;
                        console.log(url);
                        chrome.tabs.create({ url: url,windowId: tabsize.windowId} , function(tab) {
                            setTimeout(function() {
                                chrome.tabs.remove(tab.id);
                            }, 30000); // 20秒钟后关闭标签页
                        });
                    }

                }
            });
        }
    });
}, 20000);

/*
setInterval(() => {//1小时刷新刷新一次防止死掉
    chrome.tabs.query({}, function(tabs){
      const tabsize = tabs.find(v => v.url.includes('https://www.ozon.ru/?auto_get=true'))
      if (tabsize){
         chrome.tabs.reload(tabsize.id, {bypassCache: false}, function() {
          console.log("Tab reloaded with cache");
        });
      }
    });
}, 3600000);*/



var page_follow_post_time = new Date().getTime();
setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('https://www.ozon.ru/getpagefollow'))
        if (tabsize){
            if(ozon403lock == false){

                let elapsedTime = (new Date().getTime() - page_follow_post_time) / 1000;
                console.log("page_follow_post_time："+elapsedTime);

                if(elapsedTime > 500){
                    console.log("page_follow_post_time reload");
                    chrome.tabs.reload(tabsize.id);
                    //初始化时间
                    page_follow_post_time = new Date().getTime();
                }

                $.ajax({
                    url: "http://8.147.107.250/index.php?c=api/erp/follow/page_follow_get&no_sesion=1&tabid="+tabsize.id,
                    success: function (data) {
                        chrome.tabs.sendMessage(tabsize.id, data);
                    }
                });

            }else{
                console.log("getpagefollow  auto_get=true  ozon403lock");
            }
        }
    });
}, 20000);


var  item_follow_post_time = new Date().getTime();
setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('https://www.ozon.ru/getitemfollow'))
        if (tabsize){
            if(ozon403lock == false){

                let elapsedTime = (new Date().getTime() - item_follow_post_time) / 1000;
                console.log("item_follow_post_time："+elapsedTime);

                if(elapsedTime > 600){
                    console.log("item_follow_post_time reload");
                    chrome.tabs.reload(tabsize.id);
                    //初始化时间
                    item_follow_post_time = new Date().getTime();
                }

                $.ajax({
                    url: "http://8.147.107.250/index.php?c=api/erp/follow/item_follow_get&no_sesion=1&tabid="+tabsize.id,
                    success: function (data) {
                        chrome.tabs.sendMessage(tabsize.id, data);
                    }
                });
            }else{
                console.log("item_follow_get  auto_get=true  ozon403lock");
            }
        }
    });
}, 20000);


var doingListData = [];
var follow_sku_id_post_ing = new Map();
function add_follow_queue(msg){
    doingListData.push(msg);
    follow_sku_id_post_ing.set(msg.data.sku_id,true)

}

function api_send_follow_by_queue(){
    console.log("api_send_follow_by_queue start");
    console.log(doingListData.length)
    if(!doingListData || doingListData.length==0){
        setTimeout(function() {
            api_send_follow_by_queue();
        }, 10000);
        return;
    }
    console.log(follow_sku_id_post_ing);
    console.log(doingListData);
    var msg = doingListData.shift();
    $.post("http://8.147.107.250/index.php?c=api/erp/follow/search_follow_post&sku_id="+msg.data.sku_id,
        {data:msg.data.body,q:msg.data.text,cate:msg.data.category,page:msg.data.page,is_finish:msg.data.is_finish,firstpage:msg.data.firstpage,sku_id:msg.data.sku_id},
        function(data){
            if(msg.data.is_finish==1){
                follow_sku_id_post_ing.delete(msg.data.sku_id);
            }
            api_send_follow_by_queue();
        },
        "text").fail(function() {
        setTimeout(function() {
            api_send_follow_by_queue();
        }, 30000); // 20秒钟后关闭标签页
    });
}

api_send_follow_by_queue();
//ozonapi403();

/*
setInterval(() => {
    chrome.tabs.query({}, function(tabs){
      const tabsize = tabs.find(v => v.url.includes('https://www.ozon.ru/getozonsearchid?auto_get=login'))
      if (tabsize){
         if(ozon403lock==false){
             $.ajax({
                 url: "http://8.147.107.250/index.php?c=api/ozon/getozonsearchidlogin&tabid="+tabsize.id,
                 success: function (data) {
                    chrome.tabs.sendMessage(tabsize.id, data);
                 }
            });
         }else{
            console.log("getozonsearchid  auto_get=login ozon403lock");
         }
      }
    });
}, 7000);*/


setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('https://www.ozon.ru/getozonquestion'))
        if (tabsize){
            if(ozon403lock==false){

                $.ajax({
                    url: "http://47.94.147.93/index.php?c=api/erp/askGet&tabid="+tabsize.id,
                    success: function (data) {
                        console.log(data);
                        chrome.tabs.sendMessage(tabsize.id, data);
                    }
                });
            }else{
                console.log("askGet  ozon403lock");
            }
        }
    });
}, 15000);



setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('/updateamazonpics'))
        if (tabsize){
            $.ajax({
                url: "http://47.94.147.93/index.php?c=api/ozon/getamazonnopics",
                success: function (data) {
                    if(data.data.data.path){
                        var url = "https://www.amazon.com" + data.data.data.path +"?auto_get=true&amazon_id="+data.data.data.amazon_id;
                        console.log(url);
                        chrome.tabs.create({ url: url,windowId: tabsize.windowId} , function(tab) {
                            setTimeout(function() {
                                chrome.tabs.remove(tab.id);
                            }, 30000); // 20秒钟后关闭标签页
                        });
                    }

                }
            });
        }
    });
}, 10000);


setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('/updateamazonseller'))
        if (tabsize){
            if(ozon403lock==false){
                $.ajax({
                    url: "http://8.147.107.250/index.php?c=api/ozon/getseller&no_sesion=1",
                    success: function (data) {
                        if(data.data.data.seller){
                            var url = "https://www.amazon.com" + data.data.data.url +"&auto_get=true&seller_name="+data.data.data.seller;
                            console.log(url);
                            chrome.tabs.create({ url: url,windowId: tabsize.windowId} , function(tab) {
                                setTimeout(function() {
                                    chrome.tabs.remove(tab.id);
                                }, 20000); // 20秒钟后关闭标签页
                            });
                        }

                    }
                });
            }else{
                console.log("updateamazonseller ozon403lock");
            }
        }
    });
}, 10000);



setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('/updateprice1688'))
        if (tabsize){
            $.ajax({
                url: "http://47.94.147.93/index.php?c=api/ozon/getnoprice1688",
                success: function (data) {
                    if(data.data.data.spu_id){
                        var url = "https://detail.1688.com/offer/"+data.data.data.spu_id+".html?auto_get=true";
                        console.log(url);
                        chrome.tabs.create({ url: url,windowId: tabsize.windowId} , function(tab) {
                            setTimeout(function() {
                                chrome.tabs.remove(tab.id);
                            }, 30000); // 20秒钟后关闭标签页
                        });
                    }
                }
            });
        }
    });
}, 20000);





setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('https://seller.ozon.ru/app/products/add/general-info?auto_get=true'))
        if (tabsize){
            $.ajax({
                url: "http://47.94.147.93/index.php?c=api/ozon/getlimitnull",
                success: function (data) {
                    chrome.tabs.sendMessage(tabsize.id, data);
                }
            });
        }
    });
}, 9000);



setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('https://seller.ozon.ru/app/products/add/general-info?auto_get=size'))
        if (tabsize){
            $.ajax({
                url: "http://47.94.147.93/index.php?c=api/ozon/getlimitnull&type=size",
                success: function (data) {
                    chrome.tabs.sendMessage(tabsize.id, data);
                }
            });
        }
    });
}, 8000);

setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('https://seller.ozon.ru/app/products/add/general-info?auto_get=bind'))
        if (tabsize){
            $.ajax({
                url: "http://47.94.147.93/index.php?c=api/ozon/get1688catenobind",
                success: function (data) {
                    chrome.tabs.sendMessage(tabsize.id, data);
                }
            });
        }
    });
}, 8000);

setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('https://seller.ozon.ru/app/analytics/what-to-sell/ozon-bestsellers?auto_get=true'))
        if (tabsize){
            $.ajax({
                url: "http://8.147.107.250/index.php?c=api/ozon/gethotcate&tabid="+tabsize.id,
                success: function (data) {
                    chrome.tabs.sendMessage(tabsize.id, data);
                }
            });
        }
    });
}, 10000);

setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('https://seller.ozon.ru/app/analytics/what-to-sell/all-queries?auto_get=true'))
        if (tabsize){
            $.ajax({
                url: "http://8.147.107.250/index.php?c=api/erp/data/get_cate_for_query_data&tabid="+tabsize.id,
                success: function (data) {
                    chrome.tabs.sendMessage(tabsize.id, data);
                }
            });
        }
    });
}, 10000);

setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('/updateozonfontcate'))
        if (tabsize){
            $.ajax({
                url: "http://8.147.107.250/index.php?c=api/erp/cate/ozon_font_cate_type_get&tabid="+tabsize.id,
                success: function (data) {
                    chrome.tabs.sendMessage(tabsize.id, data);
                }
            });
        }
    });
}, 10000);


setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('/getozontemplate'))
        if (tabsize){
            $.ajax({
                url: "http://8.147.107.250/index.php?c=api/erp/template/template_get&tabid="+tabsize.id,
                success: function (data) {
                    chrome.tabs.sendMessage(tabsize.id, data);
                }
            });
        }
    });
}, 10000);



var lastBlockTime = null;

var lastBlockTimeYn = null;

var lastBlockTimeSheinLevel = null;

var lastBlockTimeYuenanStock = null;

function clearSheinLockYn(){
    lastBlockTimeYn = 0;
    console.log("clearSheinLockYn")
}

function clearSheinLock(){
    lastBlockTime = 0;
    console.log("clearSheinLock")
}
// 设置10分钟的时间间隔
const tenMinutes = 10 * 60 ; // 10分钟的毫秒数
const Minutes_3 = 3*60;
function setSheInBlock(domain='hk'){

    if(domain=='shein_level'){
        lastBlockTimeSheinLevel = new Date();
    }else if(domain=='yuenanstock'){
        lastBlockTimeYuenanStock = new Date();
    }else if(domain=='hk'){
        lastBlockTime = new Date();
        chrome.cookies.getAll({domain: '.shein.com.hk'}, function(cookies) {
            for (var i = 0; i < cookies.length; i++) {
                console.log("Removing cookie: " + cookies[i].name);
                chrome.cookies.remove({
                    url: "https://" + cookies[i].domain + cookies[i].path,
                    name: cookies[i].name
                }, function(details) {
                    if (details === null) {
                        console.log('Cookie not removed');
                    } else {
                        console.log('Cookie removed:', details);
                    }
                });
            }
        });
    }else{
        lastBlockTimeYn = new Date();
        chrome.cookies.getAll({domain: '.s1.shein.com'}, function(cookies) {
            for (var i = 0; i < cookies.length; i++) {
                console.log("Removing cookie: " + cookies[i].name);
                chrome.cookies.remove({
                    url: "https://" + cookies[i].domain + cookies[i].path,
                    name: cookies[i].name
                }, function(details) {
                    if (details === null) {
                        console.log('Cookie not removed');
                    } else {
                        console.log('Cookie removed:', details);
                    }
                });
            }
        });
    }
}

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

let sheinapitime = getRandomInt(61000, 71000);
console.log(sheinapitime)
setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('/sheinapi'))
        let currentTime = new Date();

        if(tabsize){
            let timeDifference = currentTime - lastBlockTime;
            if(tabsize.url.includes("s1.shein.com")){
                timeDifference = currentTime - lastBlockTimeYn;
            }
            if(tabsize){
                console.log("timeDifference sheinapi",timeDifference/1000);
                console.log(timeDifference/1000 > Minutes_3);
            }
            // 判断是否超过10分钟
            if (tabsize && timeDifference/1000 > Minutes_3){
                $.ajax({
                    url: "http://test.com:8888/index.php?c=api/neiyi/shein_detail_get&tabid="+tabsize.id,
                    success: function (data) {
                        console.log(data.data);
                        if(data.data.id){
                            chrome.tabs.sendMessage(tabsize.id, data);
                        }
                    }
                });
            }
        }

    });
}, 11000);


setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('/dubrand'))
        if (tabsize){
            $.ajax({
                url: "http://47.94.147.93/index.php?c=api/xiangshui/brand_get&tabid="+tabsize.id,
                success: function (data) {
                    console.log(data.data);
                    if(data.data.item.brand_id){
                        var url = "https://m.dewu.com/router/product/BrandDetailPage?brandId="+data.data.item.brand_id;
                        chrome.tabs.create({ url: url,windowId: tabsize.windowId,active: true} , function(tab) {
                            setTimeout(function() {
                                chrome.tabs.remove(tab.id);
                            }, 60000); // 20秒钟后关闭标签页
                        });
                    }
                }
            });
        }
    });
}, 41000);



setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('/dudetail'))

        if (tabsize){
            $.ajax({
                url: "http://47.94.147.93/index.php?c=api/xiangshui/du_get&tabid="+tabsize.id,
                success: function (data) {
                    console.log(data.data);
                    if(data.data.item.id){
                        var url = "https://dewu.com/product-detail.html?sourceName=index&spuId="+data.data.item.spu_id+"&propertyValueId=&skuId=0";
                        chrome.tabs.create({ url: url,windowId: tabsize.windowId,active: false} , function(tab) {
                            setTimeout(function() {
                                chrome.tabs.remove(tab.id);
                            }, 60000); // 20秒钟后关闭标签页
                        });
                    }
                }
            });
        }
    });
}, 41000);





var s1detailstock_tab_id = 0;
setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('/s1detailstock'))
        let currentTime = new Date();
        let timeDifference = currentTime - lastBlockTimeYuenanStock;

        if(tabsize){
            console.log("timeDifference sheindetail",timeDifference);
            console.log(timeDifference/1000 > Minutes_3);
        }
        // 判断是否超过10分钟
        if (tabsize && timeDifference/1000 > Minutes_3){
            $.ajax({
                url: "http://47.94.147.93/index.php?c=api/neiyi/shein_s1_stock_get&tabid="+tabsize.id,
                success: function (data) {
                    console.log(data.data);
                    if(data.data.id){
                        var url = "https://s1.shein.com"+ data.data.url+"?src_identifier=fc=Office%20&%20School%20Supplies`sc=Office%20&%20School%20Supplies`tc=0`oc=0`ps=tab14navbar14`jc=itemPicking_017185552&src_module=topcat&src_tab_page_id=page_select_class1738490304354&mallCode=1&pageListType=4&imgRatio=1-1&bid="+data.data.id+"&auto_get=true";
                        console.log(url);

                        chrome.tabs.get(s1detailstock_tab_id, function(tab) {
                            if (chrome.runtime.lastError) {
                                chrome.tabs.create({ url: url,windowId: tabsize.windowId,active: true} , function(tab) {
                                    s1detailstock_tab_id = tab.id;
                                });
                            } else {
                                chrome.tabs.update(s1detailstock_tab_id, { url: url });
                            }
                        });
                    }
                }
            });
        }
    });
}, 21000);

var sheindetail_tab_id = 0;
setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('/sheindetail'))
        let currentTime = new Date();
        let timeDifference = currentTime - lastBlockTime;

        if(tabsize){
            console.log("timeDifference sheindetail",timeDifference);
            console.log(timeDifference/1000 > tenMinutes);
        }
        // 判断是否超过10分钟
        if (tabsize && timeDifference/1000 > tenMinutes){
            $.ajax({
                url: "http://47.94.147.93/index.php?c=api/neiyi/shein_detail_get&tabid="+tabsize.id,
                success: function (data) {
                    console.log(data.data);
                    if(data.data.id){
                        var url = "https://www.shein.com.hk"+ data.data.url+"?src_identifier=fc=Office%20&%20School%20Supplies`sc=Office%20&%20School%20Supplies`tc=0`oc=0`ps=tab14navbar14`jc=itemPicking_017185552&src_module=topcat&src_tab_page_id=page_select_class1738490304354&mallCode=1&pageListType=4&imgRatio=1-1&bid="+data.data.id+"&auto_get=true";
                        console.log(url);
                        //var url = "https://www.shein.com.hk/api/productInfo/quickView/get?_ver=1.1.8&_lang=zh-tw&goods_id="+data.data.goods_id+"&mallCode=1&lockmall=0&isQuick=1&bid="+data.data.id;


                        chrome.tabs.get(sheindetail_tab_id, function(tab) {
                            if (chrome.runtime.lastError) {
                                chrome.tabs.create({ url: url,windowId: tabsize.windowId,active: false} , function(tab) {
                                    sheindetail_tab_id = tab.id;
                                });
                            } else {
                                chrome.tabs.update(sheindetail_tab_id, { url: url });
                            }
                        });

                    }
                }
            });
        }
    });
}, 41000);


var yuenanstock_block_time = 180;
var yuenanstock_tab_id = -1;
setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('/yuenanstock'))
        let currentTime = new Date();
        let timeDifference = currentTime - lastBlockTimeYuenanStock;
        if(tabsize){
            console.log("timeDifference yuenanstock",timeDifference,timeDifference/1000,yuenanstock_block_time);
            console.log(timeDifference/1000 > yuenanstock_block_time);
        }

        // 判断是否超过10分钟
        if (tabsize && timeDifference/1000 > yuenanstock_block_time){
            yuenanstock_tab_id = tabsize.id;
            $.ajax({
                url: "http://47.94.147.93/index.php?c=api/neiyi/shein_s1_stock_get&tabid="+tabsize.id,
                success: function (data) {
                    console.log(data.data);
                    if(data.data.id){
                        chrome.tabs.sendMessage(tabsize.id, data);
                    }
                }
            });
        }
    });
}, 11000);




var clickstock_tab_id = -1;
var clickdetail_tab_id = -1;
var click_item_array = [];
var detail_item_array = [];
setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('clickdetail'))
        // 判断是否超过10分钟
        if (tabsize){
            clickdetail_tab_id = tabsize.id;
            if(detail_item_array.length>=4){
                return;
            }
            $.ajax({
                url: "http://47.94.147.93/index.php?c=api/neiyi/shein_detail_get&tabid="+tabsize.id,
                success: function (data) {
                    console.log(data.data);
                    if(data.data.id){
                        detail_item_array.push(data);
                    }
                }
            });
        }
    });
}, 5000);



setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('clickstock'))
        // 判断是否超过10分钟
        if (tabsize){
            clickstock_tab_id = tabsize.id;
            if(click_item_array.length>=4){
                return;
            }
            $.ajax({
                url: "http://47.94.147.93/index.php?c=api/neiyi/shein_s1_stock_get_list&tabid="+tabsize.id,
                success: function (data) {
                    console.log(data.data);
                    if(data.data.list){
                        data.data.list.forEach((item) => {
                            let new_data = {};
                            new_data['data'] = item;
                            click_item_array.push(new_data);
                        });
                        console.log(click_item_array);
                    }
                }
            });
        }
    });
}, 5000);



setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('/mystock'))
        let currentTime = new Date();
        let timeDifference = currentTime - lastBlockTimeYuenanStock;
        if(tabsize){
            console.log("timeDifference yuenanstock",timeDifference);
            console.log(timeDifference/1000 > Minutes_3);
        }
        // 判断是否超过10分钟
        if (tabsize && timeDifference/1000 > Minutes_3){
            $.ajax({
                url: "http://47.94.147.93/index.php?c=api/neiyi/shein_my_stock_get&tabid="+tabsize.id,
                success: function (data) {
                    console.log(data.data);
                    if(data.data.id){
                        chrome.tabs.sendMessage(tabsize.id, data);
                    }
                }
            });
        }
    });
}, 11000);



setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('/xianggangstock'))
        let currentTime = new Date();
        let timeDifference = currentTime - lastBlockTime;
        if(tabsize){
            console.log("timeDifference xianggangstock",timeDifference);
            console.log(timeDifference/1000 > tenMinutes);
        }
        // 判断是否超过10分钟
        if (tabsize && timeDifference/1000 > tenMinutes){
            $.ajax({
                url: "http://test.com:8888/index.php?c=api/neiyi/shein_detail_level_get&tabid="+tabsize.id,
                success: function (data) {
                    console.log(data.data);
                    if(data.data.id){
                        //var url = "https://www.shein.com.hk"+ data.data.url+"?src_identifier=fc=Office%20&%20School%20Supplies`sc=Office%20&%20School%20Supplies`tc=0`oc=0`ps=tab14navbar14`jc=itemPicking_017185552&src_module=topcat&src_tab_page_id=page_select_class1738490304354&mallCode=1&pageListType=4&imgRatio=1-1&bid="+data.data.id+"&auto_get=true";
                        var url = data.data.url_stock;

                        console.log(url);
                        if(url){
                            chrome.tabs.create({ url: url,windowId: tabsize.windowId,active: false} , function(tab) {
                                setTimeout(function() {
                                    chrome.tabs.remove(tab.id);
                                }, 60000); // 20秒钟后关闭标签页
                            });
                        }

                    }
                }
            });
        }
    });
}, 10000);


setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('/sheinusersize'))
        let currentTime = new Date();
        let timeDifference = currentTime - lastBlockTimeYn;
        if(tabsize){
            console.log("timeDifference sheinlevel",timeDifference);
            console.log(timeDifference/1000 > tenMinutes);
        }
        // 判断是否超过10分钟
        if (tabsize && timeDifference/1000 > tenMinutes){
            $.ajax({
                url: "http://47.94.147.93/index.php?c=api/neiyi/shein_user_size_get&tabid="+tabsize.id,
                success: function (data) {
                    console.log(data.data);
                    if(data.data.id){
                        var url = data.data.url;
                        console.log(url);
                        if(url){
                            chrome.tabs.create({ url: url,windowId: tabsize.windowId,active: false} , function(tab) {
                                setTimeout(function() {
                                    chrome.tabs.remove(tab.id);
                                }, 60000); // 20秒钟后关闭标签页
                            });
                        }

                    }
                }
            });
        }
    });
}, 10000);


setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('/sheinlevel'))
        let currentTime = new Date();
        let timeDifference = currentTime - lastBlockTimeYn;
        if(tabsize){
            console.log("timeDifference sheinlevel",timeDifference);
            console.log(timeDifference/1000 > tenMinutes);
        }
        // 判断是否超过10分钟
        if (tabsize && timeDifference/1000 > tenMinutes){
            $.ajax({
                url: "http://47.94.147.93/index.php?c=api/neiyi/shein_s1_stock_get&tabid="+tabsize.id,
                success: function (data) {
                    console.log(data.data);
                    if(data.data.id){
                        //var url = "https://www.shein.com.hk"+ data.data.url+"?src_identifier=fc=Office%20&%20School%20Supplies`sc=Office%20&%20School%20Supplies`tc=0`oc=0`ps=tab14navbar14`jc=itemPicking_017185552&src_module=topcat&src_tab_page_id=page_select_class1738490304354&mallCode=1&pageListType=4&imgRatio=1-1&bid="+data.data.id+"&auto_get=true";
                        var url = data.data.url_stock_s1;

                        console.log(url);
                        console.log(tabsize.url)
                        if(url){
                            if(tabsize.url.includes("type=local")){
                                chrome.tabs.sendMessage(tabsize.id, data);
                            }else{
                                chrome.tabs.create({ url: url,windowId: tabsize.windowId,active: false} , function(tab) {
                                    setTimeout(function() {
                                        chrome.tabs.remove(tab.id);
                                    }, 60000); // 20秒钟后关闭标签页
                                });
                            }
                        }
                    }
                }
            });
        }
    });
}, 20000);


setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('/sheinsizepic'))
        if (tabsize){
            $.ajax({
                url: "http://test.com:8888/index.php?c=api/neiyi/shein_size_pic_get&tabid="+tabsize.id,
                success: function (data) {
                    console.log(data.data);
                    if(data.data.id){
                        var url = "http://test.com:8888/index.php?c=api/neiyi/shein_size_pic&id="+ data.data.id
                        console.log(url);
                        chrome.tabs.create({ url: url,windowId: tabsize.windowId} , function(tab) {
                            setTimeout(function() {
                                chrome.tabs.remove(tab.id);
                            }, 30000); // 20秒钟后关闭标签页
                        });
                    }
                }
            });
        }
    });
}, 10000);



/*


setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('/sheinstock'))
        if (tabsize){
            $.ajax({
                url: "http://47.94.147.93/index.php?c=api/neiyi/shein_detail_stock_get&tabid="+tabsize.id,
                success: function (data) {
                    console.log(data.data);
                    const goods_id = data.data.goods_id;
                    var url = "https://www.shein.com.hk/bff-api/product/get_goods_detail_realtime_data?_ver=1.1.8&_lang=zh-tw&goods_id="+goods_id+"&mallCode=1&isUserSelectedMallCode=1&countryId=97&state=%E9%A6%99%E6%B8%AF%2FHong+Kong&stateId=984812";

                   /!* chrome.tabs.create({ url: url,windowId: tabsize.windowId} , function(tab) {
                        setTimeout(function() {
                            chrome.tabs.remove(tab.id);
                        }, 30000); // 20秒钟后关闭标签页
                    });*!/

                    /!*if(data.data.id && data.data.goods_id){
                        chrome.tabs.sendMessage(tabsize.id, data);
                    }*!/
                }
            });
        }
    });
}, 5000);
*/



setInterval(() => {
    chrome.tabs.query({}, function(tabs){
        const tabsize = tabs.find(v => v.url.includes('/sheinajax'))
        let currentTime = new Date();
        let timeDifference = currentTime - lastBlockTime;
        if(tabsize){
            console.log("timeDifference sheinajax",timeDifference);
            console.log(timeDifference/1000 > tenMinutes);
        }
        // 判断是否超过10分钟
        if (tabsize && timeDifference/1000 > tenMinutes){
            $.ajax({
                url: "http://47.94.147.93/index.php?c=api/neiyi/shein_detail_get&tabid="+tabsize.id,
                success: function (data) {
                    console.log(data.data);
                    if(data.data.id){
                        var url = "https://www.shein.com.hk"+ data.data.url+"?src_identifier=fc=Office%20&%20School%20Supplies`sc=Office%20&%20School%20Supplies`tc=0`oc=0`ps=tab14navbar14`jc=itemPicking_017185552&src_module=topcat&src_tab_page_id=page_select_class1738490304354&mallCode=1&pageListType=4&imgRatio=1-1&bid="+data.data.id+"&auto_get=true";
                        data.data.url = url;
                        chrome.tabs.sendMessage(tabsize.id, data);
                    }
                }
            });
        }
    });
}, 71000);

let requestHeaders = {};
// 监听请求头信息

const TARGET_URL_FRAGMENT_Detail = "clickdetail";
const TARGET_URL_FRAGMENT_CLICK = "clickstock";
const TARGET_URL_FRAGMENT = "yuenanstock"; // 指定 tab 的 URL 必须包含这个片段
const TARGET_API_URL = "/api/productInfo/quickView/get"; // 监听的目标URL
const TARGET_API_URL2 = "/bff-api/product/get_goods_detail_static_data_v2"; // 监听的目标URL
const TARGET_API_URL3 = "/bff-api/product/get_goods_detail_realtime_data"; // 监听的目标URL



function isValidImageUrl(url) {
    url = url.replace("http://", "https://");
    const regex = /^https:\/\/img\.ltwebstatic\.com\/.*\.png$/;
    return regex.test(url);
}
// 监听所有web请求


chrome.webRequest.onBeforeSendHeaders.addListener(
    (details) => {

        if (isValidImageUrl(details.url) && !details.url.includes("bid") && !details.url.includes(".webp") && !details.url.includes(".webp")){
            console.log("sm_pic",details.url,details.tabId,s1detailstock_tab_id);
            chrome.tabs.sendMessage(s1detailstock_tab_id, { type: "sm_pic", pic: details.url });
            chrome.tabs.sendMessage(details.tabId, { type: "sm_pic", pic: details.url });
        }

        //console.log("details.tabId,clickstock_tab_id",details.tabId,clickstock_tab_id)
        if(details.url==='https://img.ltwebstatic.com/images3_acp/2024/05/07/b5/17150867820f2e16f94fe21984a46aeefdab7fb4e4.png'
            || details.url==='https://img.ltwebstatic.com/images3_ps1/2024/08/26/ca/1724637873211f5f99c43c9e6b042b71915f296ffe_thumbnail_405x.png'
        ){
            //do nune
        }else if(details.tabId===-1){
            if (details.url.includes(TARGET_API_URL) && !details.url.includes("bid")) {
                const headers = details.requestHeaders;
                console.log(headers);
                // 发送消息到 content.js
                chrome.tabs.sendMessage(yuenanstock_tab_id, { type: "header_quickView", headers: headers });
            }else  if ( details.url.includes(TARGET_API_URL2) && !details.url.includes("bid")){
                const headers = details.requestHeaders;
                console.log(headers);
                // 发送消息到 content.js
                chrome.tabs.sendMessage(yuenanstock_tab_id, { type: "header_static_v2", headers: headers });
            }else  if ( details.url.includes(TARGET_API_URL3) && !details.url.includes("bid")){
                const headers = details.requestHeaders;
                console.log(headers);
                // 发送消息到 content.js
                chrome.tabs.sendMessage(yuenanstock_tab_id, { type: "header_realtime", headers: headers });
            }
        }else if(details.tabId===yuenanstock_tab_id){
            // 获取当前活动的标签页信息
            chrome.tabs.get(details.tabId, (tab) => {
                if (tab.url.includes(TARGET_URL_FRAGMENT) && details.url.includes(TARGET_API_URL) && !details.url.includes("bid")) {
                    const headers = details.requestHeaders;
                    console.log(headers);
                    // 发送消息到 content.js
                    chrome.tabs.sendMessage(tab.id, { type: "header_quickView", headers: headers });
                }else  if (tab.url.includes(TARGET_URL_FRAGMENT) && details.url.includes(TARGET_API_URL2) && !details.url.includes("bid")){
                    const headers = details.requestHeaders;
                    console.log(headers);
                    // 发送消息到 content.js
                    chrome.tabs.sendMessage(tab.id, { type: "header_static_v2", headers: headers });
                }else  if (tab.url.includes(TARGET_URL_FRAGMENT) && details.url.includes(TARGET_API_URL3) && !details.url.includes("bid")){
                    const headers = details.requestHeaders;
                    console.log(headers);
                    // 发送消息到 content.js
                    chrome.tabs.sendMessage(tab.id, { type: "header_realtime", headers: headers });
                }
            });
        }/*else if(details.tabId===clickstock_tab_id){
            // 获取当前活动的标签页信息
            chrome.tabs.get(details.tabId, (tab) => {
                if (tab.url.includes(TARGET_URL_FRAGMENT_CLICK) && isValidImageUrl(details.url) && !details.url.includes("bid") && !details.url.includes(".webp")){
                    console.log("sm_pic",details.url);
                    chrome.tabs.sendMessage(tab.id, { type: "sm_pic", pic: details.url });
                }
            });
        }else if(details.tabId===clickdetail_tab_id){
            // 获取当前活动的标签页信息
            chrome.tabs.get(details.tabId, (tab) => {
                if (tab.url.includes(TARGET_URL_FRAGMENT_Detail) && isValidImageUrl(details.url) && !details.url.includes("bid") && !details.url.includes(".webp")){
                    console.log("sm_pic",details.url);
                    chrome.tabs.sendMessage(tab.id, { type: "sm_pic", pic: details.url });
                }
            });
        }*/
    },
    { urls: ["<all_urls>"] },
    ["blocking", "requestHeaders"]
);

//拦截url，然后改写

// 监听请求

var click_item_array_ing = {};
var detail_item_array_ing = {};
chrome.webRequest.onBeforeRequest.addListener(
    function (details) {

        // 只处理特定 tab 的请求
        const tabId = details.tabId;
        if ((tabId !== clickdetail_tab_id &&  tabId !== clickstock_tab_id )|| tabId === -1) {
            // console.log("tabId??clickstock_tab_id??clickdetail_tab_id", tabId, clickstock_tab_id,clickdetail_tab_id);
            return; // 直接返回
        }

        // 检查标签页的 URL 是否包含特殊名
        // 这里我们直接使用 tabId 进行过滤，可以省略 chrome.tabs.get
        if (tabId === clickstock_tab_id && !details.url.includes("bid")) {
            // 直接从请求的 URL 判断
            if (details.url.includes(TARGET_API_URL) ||
                details.url.includes(TARGET_API_URL2) ||
                details.url.includes(TARGET_API_URL3)) {
                if(click_item_array.length===0){
                    return ;
                }
                let replace_item = click_item_array.shift();
                if(replace_item){
                    // 使用 URL 对象解析和修改 URL
                    const url = new URL(details.url);
                    // 添加或修改查询参数
                    url.searchParams.set("goods_id", replace_item.data.goods_id);
                    url.searchParams.set("bid", replace_item.data.id);
                    click_item_array_ing[replace_item.data.id] = replace_item;
                    console.log("click_item_array_ing",click_item_array_ing);
                    console.log(`Request modified from ${details.url} to ${url.href} for tab: ${tabId}`);
                    // 返回修改后的 URL
                    return { redirectUrl: url.toString() };
                }

            }
        }else if (tabId === clickdetail_tab_id && !details.url.includes("bid")) {
            // 直接从请求的 URL 判断
            if (/*details.url.includes(TARGET_API_URL) ||*/
                details.url.includes(TARGET_API_URL2)
            ) {
                if(detail_item_array.length===0){
                    return ;
                }
                let replace_item = detail_item_array.shift();
                if(replace_item){
                    // 使用 URL 对象解析和修改 URL
                    const url = new URL(details.url);
                    // 添加或修改查询参数
                    url.searchParams.set("goods_id", replace_item.data.goods_id);
                    url.searchParams.set("bid", replace_item.data.id);
                    detail_item_array_ing[replace_item.data.id] = replace_item;
                    console.log("detail_item_array_ing",detail_item_array_ing);
                    console.log(`detail=>Request modified from ${details.url} to ${url.href} for tab: ${tabId}`);
                    // 返回修改后的 URL
                    return { redirectUrl: url.toString() };
                }

            }
        }
    },
    { urls: ["<all_urls>"] }, // 可以配置具体需要的 url 过滤
    ["blocking"]
);

/*
const TARGET_URL_FRAGMENT = "sheinapi"; // 指定 tab 的 URL 必须包含这个片段
const TARGET_API_URL = "https://www.shein.com.hk/api/productInfo/quickView/get"; // 监听的目标URL

// 监听所有web请求
chrome.webRequest.onBeforeSendHeaders.addListener(
    (details) => {
        // 获取当前活动的标签页信息
        chrome.tabs.get(details.tabId, (tab) => {
            if (tab.url.includes(TARGET_URL_FRAGMENT) && details.url.includes(TARGET_API_URL) && !details.url.includes("bid")) {
                const headers = details.requestHeaders;
                console.log(headers);
                // 发送消息到 content.js
                chrome.tabs.sendMessage(tab.id, { type: "LOG_REQUEST", headers: headers });

            }
        });
    },
    { urls: ["<all_urls>"] },
    ["blocking", "requestHeaders"]
);*/

/*
let requestHeaders = {};
// 监听请求头信息
chrome.webRequest.onBeforeSendHeaders.addListener(
    function(details) {
        // 存储请求的 header 信息
        requestHeaders[details.requestId] = details.requestHeaders;
        console.log(details.requestHeaders);
    },
    { urls: ["https://app.dewu.com/api/v1/h5/pc/index/fire/flow/product/detailV3*"] },
    ["requestHeaders"] // 需要 requestHeaders 权限
);*/
/*
chrome.webRequest.onBeforeRequest.addListener(
    function(details) {

        setTimeout(() => {
            console.log(details);
            console.log(details.requestBody);

            const rawData = details.requestBody.raw[0].bytes;
            const decoder = new TextDecoder("utf-8");
            const bodyString = decoder.decode(rawData);
            console.log("Raw Body:", bodyString);

            if (details.method === "POST" || details.method === "GET") {

                const tabId = details.tabId;
                const url = details.url;
                const headers = requestHeaders[details.requestId] || [];
                console.log("Request Headers:", headers);
                // 获取请求信息
                const requestData = {
                    tabId,
                    url,
                    method: details.method,
                    requestHeaders: headers,
                    requestBody: bodyString,
                };
                // 发送消息到 content script
                chrome.tabs.sendMessage(tabId, { action: "sendRequest", requestData });
            }
        }, 2000);
    },
    { urls: ["https://app.dewu.com/api/v1/h5/pc/index/fire/flow/product/detailV3*"] },
    ["blocking","requestBody"]
);*/


const targetUrlSubstring = 'clickstock';
const targetUrlSubstringDetail = 'clickdetail';
let attachedTabId = null;
let requestIdMap = {}; // 存储有效请求 ID

// 处理标签页更新事件
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    if (changeInfo.status === 'complete' && tab.url.includes(targetUrlSubstring)) {
        if (attachedTabId === tabId) {
            console.log("Debugger already attached to tab: ", tabId);
            return; // 跳过绑定
        }
        attachDebugger(tabId);
    }else if (changeInfo.status === 'complete' && tab.url.includes(targetUrlSubstringDetail)) {
        if (attachedTabId === tabId) {
            console.log("Debugger already attached to tab: ", tabId);
            return; // 跳过绑定
        }
        attachDebugger(tabId);
    }
});

// 附加调试器的函数
function attachDebugger(tabId) {
    if (!tabId) {
        console.error("Invalid tabId: ", tabId);
        return;
    }

    if (attachedTabId !== null) {
        detachDebugger(attachedTabId);
    }

    console.log("Attaching debugger to tab: ", tabId);
    attachedTabId = tabId;

    chrome.debugger.attach({ tabId: attachedTabId }, "1.3", () => {
        if (chrome.runtime.lastError) {
            console.error("Failed to attach debugger: ", chrome.runtime.lastError);
            attachedTabId = null;
            return;  // 确保 error 时只保留一份
        }
        console.log("Debugger attached to tab: ", attachedTabId);
        chrome.debugger.sendCommand({ tabId: attachedTabId }, "Network.enable");
    });
}

// 解除调试器的绑定
function detachDebugger(tabId) {
    if (!tabId) {
        console.error("Invalid tabId: ", tabId);
        return;
    }

    console.log("Detaching debugger from tab: ", tabId);
    chrome.debugger.detach({ tabId: tabId }, () => {
        console.log("Debugger detached from tab: ", tabId);
        if (tabId === attachedTabId) {
            attachedTabId = null;
        }
    });
}

function getUrlParameter(url, key) {
    const urlObj = new URL(url); // 创建 URL 对象
    return urlObj.searchParams.get(key); // 获取指定参数的值
}

var PIC_CHECK_URL='/risk/verify/identity/validation/resources';
function getResponseBodyWithDelay(url,tabId, requestId, delay) {
    setTimeout(() => {
        chrome.debugger.sendCommand({ tabId }, "Network.getResponseBody", { requestId }, (body) => {
            if (chrome.runtime.lastError) {
                console.error("Failed to get response body: ", chrome.runtime.lastError);
            } else {
                let type = "";
                if(url.includes(PIC_CHECK_URL)){
                    body['type'] = "token_check";
                    chrome.tabs.sendMessage(tabId, body);
                }else if(url.includes(TARGET_API_URL)){
                    type = 'quick';
                }else if(url.includes(TARGET_API_URL2)){
                    type = 'static';
                }else if(url.includes(TARGET_API_URL3)){
                    type = 'realtime';
                }else{
                    return
                }
                let bid = getUrlParameter(url,"bid");
                if(bid){
                    console.log('Response body:', body);

                    let api_error = false;
                    if(body['body'].includes("cookie_duration")){
                        api_error=true;
                    }

                    body['bid'] = bid;
                    body['type'] = type;
                    if(tabId===clickstock_tab_id){
                        if(api_error===true){
                            click_item_array.unshift(click_item_array_ing[bid]);
                        }else{
                            body['msg'] = click_item_array_ing[bid];
                            chrome.tabs.sendMessage(tabId, body);
                        }

                        delete click_item_array_ing[bid];
                    }else if(tabId===clickdetail_tab_id){
                        if(api_error===true){
                            detail_item_array.unshift(detail_item_array_ing[bid]);
                        }else{
                            body['msg'] = detail_item_array_ing[bid];
                        }
                        chrome.tabs.sendMessage(tabId, body);
                        delete detail_item_array_ing[bid];
                    }
                }
            }
        });
    }, delay);
}


// 处理网络请求
chrome.debugger.onEvent.addListener((source, method, params) => {
    // 记录有效请求 ID
    /*if (method === "Network.requestWillBeSent") {
        requestIdMap[params.requestId] = true; // 存储请求 ID
    }*/

    if (method === "Network.responseReceived" && source.tabId === attachedTabId) {
        const { response } = params;
        const requestId = params.requestId;
        if (response.url.includes("bid")
            &&
            (   response.url.includes(TARGET_API_URL)
                || response.url.includes(TARGET_API_URL2)
                || response.url.includes(TARGET_API_URL3)
            )
        ) {
            console.log(response.url);
            getResponseBodyWithDelay(response.url,source.tabId, requestId, 500);
        }else if(response.url.includes(PIC_CHECK_URL)){
            getResponseBodyWithDelay(response.url,source.tabId, requestId, 500);
        }

        delete requestIdMap[requestId]; // 处理完后删除请求 ID
    }
});

// 处理调试器解除事件
chrome.debugger.onDetach.addListener((source) => {
    console.log("Debugger detached for tab: ", source.tabId);
});
